<?php
namespace backend\components;

use Yii;
use yii\helpers\ArrayHelper;
use backend\components\Utools;
use backend\modules\admin\models\ReleasePoint;
use backend\modules\admin\models\Site;
use backend\components\Ftp;
use backend\modules\content\models\Category;
use backend\modules\admin\models\Urlrule;


/**
 * @author libin
 * @time 2018 1 11
 * @for 
 * Url生成类 根据Url规则，生成栏目以及尾页url
*/
class Urls{

	public $siteid=1;
    public $categorys=array();
	public $urlrules=array();
	public $web_path='/';
	public function __construct() {
		$this->siteid = Utools:: get_siteid();//得到当前站点id
        $categorys=Category::find()->where(array('siteid'=>$this->siteid,'status'=>0))->asArray()->all();//查出当前站点未删除可显示的全部数据
        $urlrules = Urlrule::find()->where(array('status'=>0))->asArray()->all();//查出所有的urlrule中的数据
		foreach($categorys as $cat)
		{
			$categorysT[$cat['catid']]=$cat;  //使key键值和catid相对应，是一样的
		}
		$this->categorys=$categorysT;

        foreach($urlrules as $url)
		{
			$urlrulesT[$url['urlruleid']]=$url;   //使key键值和urlruleid相对应，是一样的
		}
		$this->urlrules=$urlrulesT;

	}

	/**
	 * @author dingzhibiao
	 * 2018.1.11
	 * 初步完成show
	 */
	
	/**
	 * 内容页链接
	 * @param $id 内容id
	 * @param $page 当前页
	 * @param $catid 栏目id
	 * @param $time 添加时间
	 * @param $prefix 前缀
	 * @param $data 数据
	 * @param $action 操作方法
	 * @param $upgrade 是否是升级数据
	 * @return array 0=>url , 1=>生成路径
	 */
	public function show($id, $page = 0, $catid = 0, $time = 0, $prefix = '',$data = '',$action = 'edit') 
	{
		$site = Site::findOne(['siteid' => $this->siteid]);
		$domain = $site->domain;//获取当前站点的域名
		$page = max($page,1);//获取当前页的最大值
		$urls = $catdir = '';
		$category = $this->categorys[$catid];//获取到$catid的这一条数据
		
		$content_ishtml = $category['content_ishtml'];//查出content_ishtml的值
		$show_ruleid = $category['show_ruleid'];//查出show_ruleid的值
		$urlrules = $this->urlrules[$show_ruleid]['urlrule'];//查出urlrule表中urlruleid=show_ruleid数据中的urlrule

		$site=Site::findOne($category['siteid']);
		if(!$site)
		{
			exit('站点不存在');
		}
	

		if(!$time) $time = SYS_TIME;//判断出当前时间
		$urlrules_arr = explode('|',$urlrules);//用'|'分割获取到的urlrule
		if($page==1) //如果当前页为1，输出分割得到的$urlrules_arr[0],否则输出$urlrules_arr[1] 
		{
			$urlrule = $urlrules_arr[0];
		} 
		else
		{
			$urlrule = isset($urlrules_arr[1]) ? $urlrules_arr[1] : $urlrules_arr[0]; //判断$urlrules_arr有没有第二组数据，如果有就输出，没有就输出第一组数据
		}
		$domain_dir = '';
		if (0&&strpos($category['url'], '://')!==false && strpos($category['url'], '?')===false)//当url中有'：//'但是没有'?'时执行
		{
			//看url和正则表达式是否匹配
			if (preg_match('/^((http|https):\/\/)?([^\/]+)/i', $category['url'], $matches))
			{
				$match_url = $matches[0]; //$matches[0]将包含完整模式匹配到的文本，$matches[1] 将包含第一个捕获子组匹配到的文本
				$url = $match_url.'/';
			}
			$r = Category::find()->select('catid')->where(['url'=>$url])->asArray()->one();
			
			if($r) $domain_dir = $this->get_categorydir($r['catid']).$this->categorys[$r['catid']]['catdir'].'/';
			
		}
		$categorydir = $this->get_categorydir($catid);//获取到catid的父栏目路径
		$catdir = $category['catdir'];//获取该catid数据中catdir的值
		$year = date('Y',$time);//当前年份
		$month = date('m',$time);//当前月
		$day = date('d',$time);//当前天
		//将urlrule中的数据进行替换
		$urls = str_replace(array('{$categorydir}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$id}','{$page}'),array($categorydir,$catdir,$year,$month,$day,$catid,$id,$page),$urlrule);
		//获取到当前catid数据中creat_to_html_root的值，看是否要发送到根目录
		$creat_to_html_root = $category['creat_to_html_root'];
		
		if($creat_to_html_root || $category['sethtml']) //判断是否发送到根目录或者是否设置为Html，两者满足其一即可
		{
			$html_root = '';
		} 
		else 
		{
			$html_root = 'html/';
		}
		if(0&&$content_ishtml && $url) 
		{
			if ($domain_dir && $category['isdomain']) 
			{
				$url_arr[1] = $html_root.'/'.$domain_dir.$urls;
				$url_arr[0] = $url.$urls;
			} 
			else 
			{
				$url_arr[1] = $html_root.'/'.$urls;
				$url_arr[0] = $this->web_path == '/' ? $match_url.$html_root.'/'.$urls : $match_url.rtrim($this->web_path,'/').$html_root.'/'.$urls;
			}
		} 
		elseif($content_ishtml) //静态类型的url
		{
			
			$url_arr[0] = $site->domain.$html_root.$urls;
			$url_arr[1] = $html_root.$urls;
		} 
		else //动态类型的url
		{
			$url_arr[0] = $url_arr[1] =$site->domain.$urls;
		}		
		//生成静态 ,在添加文章的时候，同时生成静态，不在批量更新URL处调用
		if($content_ishtml && $data) 
		{
			$data['id'] = $id;
			$url_arr['content_ishtml'] = 1;
			$url_arr['data'] = $data;
		}
		return $url_arr;
	}
	
	/**
	 * 获取栏目的访问路径
	 * 在修复栏目路径处重建目录结构用
	 * @param intval $catid 栏目ID
	 * @param intval $page 页数
	 */
	public function category_url($catid, $page = 1) 
	{
		$site = Site::findOne(['siteid' => $this->siteid]);
		$domain = $site->domain;//获取当前站点的域名
		$category = $this->categorys[$catid];//获取到$catid的这一条数据
		if($category['type']==2) return $category['url'];//type=2,外部链接
		$page = max(intval($page), 1);//获取当前页的最大值的整数值
		$category_ruleid = $category['category_ruleid'];//查出category_ruleid的值
		$urlrules = $this->urlrules[$category_ruleid]['urlrule'];//查出urlrule表中urlruleid=category_ruleid数据中的urlrule
		$urlrules_arr = explode('|',$urlrules);//用'|'分割获取到的urlrule

		$site=Site::findOne($category['siteid']);
		if(!$site)
		{
			exit('站点不存在');
		}


		if ($page==1) //如果当前页为1，输出分割得到的$urlrules_arr[0],否则输出$urlrules_arr[1]
		{
			$urlrule = $urlrules_arr[0];
		} 
		else 
		{
			$urlrule = $urlrules_arr[1];
		}
		if (!$category['ishtml']) //ishtml=0时，直接输出url
		{ //如果不生成静态
			$url = str_replace(array('{$catid}', '{$page}'), array($catid, $page), $urlrule);//替换
			if (strpos($url, '\\')==false) // url存在'\\'
			{
				$url = $domain.str_replace('\\', '/', $url);//把url中的'\\'替换成'/'
			}
		}
		else 
		{ //生成静态
			if ($category['arrparentid']) 
			{
				$parentids = explode(',', $category['arrparentid']);//分割arrparentid，形成数组
				unset($parentids[0]);
			}
			$parentids[] = $catid;//将此catid也加入到分割得到的arrparentids数组中
			$domain_dir = '';//域名目录

			foreach ($parentids as $pid) 
			{ 
				if($pid==0) continue;
				$r = $this->categorys[$pid];//得到所包含的父id的所有数据
				if (strpos(strtolower($r['url']), '://')!==false && strpos($r['url'], '?')===false) //循环查询父栏目是否设置了二级域名；当url中有'：//'但是没有'?'时执行
				{	
					$r['url'] = preg_replace('/([(http|https):\/\/]{0,})([^\/]*)([\/]{1,})/i', '$1$2/', $r['url'], -1); //取消掉双'/'情况
					if (substr_count($r['url'], '/')==3 && substr($r['url'],-1,1)=='/') 
					{ //如果url中包含'http://'并且'/'在3个则为二级域名设置栏目
						$url = $r['url'];
						$domain_dir = $this->get_categorydir($pid).$this->categorys[$pid]['catdir'].'/'; //得到二级域名的目录
					}
				}
			}
			$category_dir = $this->get_categorydir($catid);//得到父栏目路径即catdir
			$urls = str_replace(array('{$categorydir}','{$catdir}','{$catid}','{$page}'),array($category_dir,$category['catdir'],$catid,$page),$urlrule);//替换路径中的变量
			if (0&&$url && $domain_dir) 
			{ //如果存在设置二级域名的情况
				if (strpos($urls, $domain_dir)===0) 
				{
					$url = str_replace(array($domain_dir, '\\'), array($url, '/'), $urls);
				} 
				else 
				{
					$urls = $domain_dir.$urls;
					$url = str_replace(array($domain_dir, '\\'), array($url, '/'), $urls);
				}
			} 
			else 
			{ //不存在二级域名的情况
				$url = $urls;
			}
		}
		//basename返回路径中文件名部分；in_array函数搜索数组中是否存在指定的值
		if (in_array(basename($url), array('index.html', 'index.htm', 'index.shtml'))) 
		{
			$url = dirname($url).'/';//dirname函数返回路径中的目录部分
		}
		if (strpos($url, '://')===false) $url = str_replace('//', '/', $url);
		if(strpos($url, '/')===0) $url = substr($url,1);
		return $url;
	}
	/**
	 * 生成列表页分页地址
	 * @param $ruleid 角色id
	 * @param $categorydir 父栏目路径
	 * @param $catdir 栏目路径
	 * @param $catid 栏目id
	 * @param $page 当前页
	 */
	public function get_list_url($ruleid,$categorydir, $catdir, $catid, $page = 1) 
	{
		$urlrules = $this->urlrules[$ruleid];
		
		$urlrules_arr = explode('|',$urlrules['urlrule']);
		if ($page==1) 
		{
			$urlrule = $urlrules_arr[0];
		} 
		else 
		{
			$urlrule = $urlrules_arr[1];
		}
		$time=time();
		$year = date('Y',$time);
		$month = date('m',$time);
		$day = date('d',$time);
		$urls = str_replace(array('{$categorydir}','{$catdir}','{$year}','{$month}','{$day}','{$catid}','{$page}'),array($categorydir,$catdir,$year,$month,$day,$catid,$page),$urlrule);
		return $urls;
	}
	
	/**
	 * 获取父栏目路径
	 * @param $catid
	 * @param $dir
	 */
	public function get_categorydir($catid, $dir = '') 
	{
		$setting = array();
		$setting = Utools::string2array($this->categorys[$catid]['creat_to_html_root']);
		if ($setting['creat_to_html_root']) return $dir;
		if ($this->categorys[$catid]['parentid']) 
		{
			$dir = $this->categorys[$this->categorys[$catid]['parentid']]['catdir'].'/'.$dir;
			return $this->get_categorydir($this->categorys[$catid]['parentid'], $dir);
		} 
		else 
		{
			return $dir;
		}
	}
	public function get_categoryid($catid) 
	{
		if($this->categorys[$catid]['parentid'] == 0)
		{
			return null;
		}
		else
		{
			$parentid = $this->categorys[$this->categorys[$catid]['parentid']]['parentid'];
			if($parentid ==0)
			{
				return $this->categorys[$catid]['parentid'];
			}
			else
			{
				$arrparentid = $this->categorys[$this->categorys[$catid]['parentid']]['parentid'].','.$this->categorys[$catid]['parentid'];	
				return $arrparentid;
			}
		}
	}
	/**
	 * 设置当前站点
	 */
	/*
	private function set_siteid() 
	{
		if(defined('IN_ADMIN')) 
		{
			$this->siteid = get_siteid();
		} 
		else 
		{
			if (param::get_cookie('siteid')) 
			{
				$this->siteid = param::get_cookie('siteid');
			} 
			else 
			{
				$this->siteid = 1;
			}
		}
	}*/

}
